package com.daykw.douyin.task;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.nutz.dao.impl.NutDao;

import com.daykw.douyin.config.NutzDaoConfig;
import com.daykw.douyin.http.HttpBase;
import com.daykw.douyin.model.VideoAuth;
import com.daykw.douyin.model.VideoInfo;
import com.daykw.douyin.model.VideoTask;
import com.daykw.douyin.utils.SpringContextHolder;

public class VideoAuthVideoThread extends Thread {

	private static Logger logger = Logger.getLogger(VideoAuthVideoThread.class);
	private NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);

	@Override
	public void run() {
		try {
			List<VideoAuth> auths = dao.query(VideoAuth.class,
					Cnd.where("status", "=", 2).and("video_status", "=", 0).limit(1, 20).desc("search"));

			HttpBase http = new HttpBase();
			Map<String, String> headers = new HashMap<String, String>();
			Record c = dao.fetch("t_cookie", Cnd.where("name", "=", "13235801201"));
			if (c == null) {

				logger.info("cookie:13235801201没了...");
				return;
			}
			String cookie = c.getString("cookie");
			for (VideoAuth auth : auths) {

				headers.put("Cookie", cookie);

				for (int i = 1; i <= 10; i++) {
					String surl = "https://dy.feigua.cn/Blogger/AwemeList?page=" + i + "&id=" + auth.getDataid()
							+ "&shop=0&sort=1&keyword=";

					Map<String, String> data = new HashMap<String, String>();
					data.put("Host", "dsp.feigua.cn");
					data.put("User-Agent",
							"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36");
					String html = http.get(surl, headers);

					if (!html.equals("302")) {

						Document doc = Jsoup.parse(html);
						Elements ds = doc.select("div.v-main div.dn-results.icon-search-result");
						if (ds.text().indexOf("立即升级会员版本") > 0) {
							dao.update(VideoAuth.class, Chain.make("video_status", 2),
									Cnd.where("dataid", "=", auth.getDataid()));
							logger.info(auth.getKw_nick_name() + "账号下的视频全部完毕");
							return;
						}
						if (StringUtil.isBlank(html)) {
							dao.update(VideoAuth.class, Chain.make("video_status", 2),
									Cnd.where("dataid", "=", auth.getDataid()));
							logger.info(auth.getKw_nick_name() + "账号下的视频全部完毕");
							return;
						}
						Elements trs = doc.select("table.table tbody tr");

						if (trs.text().indexOf("抱歉，暂无数据结果") >= 0) {
							dao.update(VideoAuth.class, Chain.make("video_status", 2),
									Cnd.where("dataid", "=", auth.getDataid()));
							continue;
						}

						for (Element tr : trs) {
							// String nickname = doc.select("div.info div.nickname").text();
							Element a = tr.select("div.media-list div.item-media a").first();
							String dataid = a.attr("data-id");
							String awemeid = a.attr("data-awemeid");
							String img = tr.select("div.media-list div.item-media a img").attr("src");
							String title = tr.select("div.media-list div.item-title a").text();

							String authurl = auth.getAuth_url();
							String infourl = "https://dy.feigua.cn/Aweme/Detail?id=" + dataid + "&awemeId=" + awemeid
									+ "&active=detail";

							this.saveData(dataid, awemeid, infourl, authurl, img, auth.getKw_uid(),
									auth.getKw_nick_name());

						}
						dao.update(VideoAuth.class, Chain.make("video_status", 2),
								Cnd.where("dataid", "=", auth.getDataid()));
						logger.info(auth.getKw_nick_name() + "账号下的视频搜索完毕,第" + i + "页");
						Thread.sleep(5000);
					}
				}

			}

		} catch (Exception e) {
			logger.error("", e);
		}

	}

	private void saveData(String dataid, String awemeid, String url, String auth_url, String img, String uid,
			String nickname) {
		SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
		VideoTask task = dao.fetch(VideoTask.class, Cnd.where("kw_id", "=", awemeid));

		if (task == null) {
			task = new VideoTask();

			task.setInfo_url(url);
			task.setDataid(dataid);
			task.setKw_id(awemeid);

			task.setAuth_url(auth_url);

			task.setInfo_status(0);
			task.setUid_status(0);
			task.setCmt_status(0);
			task.setEc_status(5);
			task.setCreate_time(new Date());

			task.setCdate(Integer.parseInt(fmt.format(new Date())));
			try {
				dao.fastInsert(task);
			} catch (Exception e) {
				logger.error("", e);
			}

			VideoInfo video = new VideoInfo();

			video.setHas_product(0);
			if (StringUtils.isNotEmpty(nickname)) {
				video.setKw_auth_name(nickname);
			}

			video.setKw_head_image(img);
			video.setDataid(dataid);
			video.setKw_id(awemeid);
			if (StringUtils.isNotEmpty(uid)) {
				video.setKw_uid(uid);
				video.setKw_auth_url("https://www.iesdouyin.com/share/user/" + uid);
			}

			video.setCreate_time(new Date());
			video.setCdate(Integer.parseInt(fmt.format(new Date())));
			try {
				dao.fastInsert(video);
			} catch (Exception e) {
				logger.error("", e);
			}

		} else {
			// logger.info("awemeid重复：" + awemeid);
		}
	}
}
